﻿using System;
using System.Linq.Expressions;

namespace NiuX.Dapper.Extensions;

public static class ExpressionExtensions
{
    /// <summary>
    /// 转换成一元表达式并取值
    /// </summary>
    /// <param name="expression"></param>
    /// <returns></returns>
    public static object ToConvertAndGetValue(this Expression expression)
    {
        if (expression.Type != typeof(object))
            expression = Expression.Convert(expression, typeof(object));

        var lambdaExpression = Expression.Lambda<Func<object>>(expression);
        return lambdaExpression.Compile().Invoke();
    }

    public static string TransferExpressionType(this ExpressionType expressionType)
    {
        string type = "";
        switch (expressionType)
        {
            case ExpressionType.Equal:
                type = "="; break;
            case ExpressionType.GreaterThan:
                type = ">"; break;
            case ExpressionType.GreaterThanOrEqual:
                type = ">="; break;
            case ExpressionType.LessThan:
                type = "<"; break;
            case ExpressionType.LessThanOrEqual:
                type = "<="; break;
            case ExpressionType.NotEqual:
                type = "!="; break;
            case ExpressionType.AndAlso:
                type = "And"; break;
            case ExpressionType.OrElse:
                type = "Or"; break;
            default:
                throw new ArgumentOutOfRangeException(nameof(expressionType), expressionType, null);
        }
        return type;
    }
}